package cn.codeforfun.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;

import java.io.IOException;

/**
 * Package cn.codeforfun.util
 * Project framework-demo
 * Author WangBin
 * Email bin.wang12@pactera.com
 * Created on 2017/5/3 16:42
 * version 1.0.0
 */
public class OKHttpUtil {
  private static final OkHttpClient client = new OkHttpClient();
  public static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

  public static String get(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
  }

  public static String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON_TYPE, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
  }

  public static String post(String url, Object obj) throws IOException {
    ObjectMapper om = new ObjectMapper();
    String s = om.writeValueAsString(obj);
    return OKHttpUtil.post(url, s);
  }
}
